package com.eric.windows.annotations;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.eric.windows.MyApplication;
import com.eric.windows.R;
import com.eric.windows.event.CircleTestActivity;
import com.eric.windows.event.CircleTestActivity_;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.HttpsClient;
import org.androidannotations.annotations.InstanceState;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;

@EActivity(R.layout.activity_configuration_test)
public class AATestActivity extends Activity  {

     @ViewById(R.id.txt_configuration)
     TextView txt_configuration;
     @ViewById
     TextView txt_configuration2;
     @ViewById
     TextView txt_configuration3;
     @ViewById
     TextView txt_configuration4;
     @ViewById
     TextView txt_configuration5;
     @ViewById(R.id.img_conf)
     ImageView imageView;
     /**初始化变量 当onSaveInstanceState(Bundle)回调时 这些值将自动保存  */
     @InstanceState
     String def;
     @App
     MyApplication myApplication;
    /** 通过id 找fragment*/
//    @FragmentById(R.id.myFragment)
//    MyAAFragment myAAFragment;
    /**
     * 将在ConfigurationTestActivity_中声明一个静态变量，这个变量值是由intent（其他界面跳转到该界面使用intent ）中获取的 ，如：
     * public final static String MY_MESSAGE_EXTRA = "myStringExtra"; 使用 参见 {@link CircleTestActivity#myMessage}
     */
    @Extra("myStringExtra")
    String myMessage;
//    @Extra("myDateExtra")
//    Date myDateExtraWithDefaultValue = new Date();

    @Pref
    MyPrefs_ myPrefs;

    @HttpsClient
    HttpClient httpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    //一般在这个方法中初始化views
    @AfterViews
    void initView(){
        //configuration 对象示例
        Configuration configuration  = getResources().getConfiguration();
        //屏幕的方向
        int orientation = configuration.orientation;
        switch (orientation){
            case Configuration.ORIENTATION_LANDSCAPE:
                txt_configuration.setText("横向屏幕");
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                txt_configuration.setText("竖向屏幕");
                break;
            case Configuration.ORIENTATION_SQUARE:
                txt_configuration.setText("方形屏幕");
                break;
            case Configuration.ORIENTATION_UNDEFINED:
                txt_configuration.setText("没有屏幕屏幕方向");
                break;
        }


        getData();
        txt_configuration3.setText(myApplication.userBean.userName);

        Bundle bundle = new Bundle();
        bundle.putString("stringArgExtra","Arg数据");
        //创建一个MyAAFragment实例
        MyAAFragment myFragment = MyAAFragment_.builder()
                .arg(bundle)
                .build();
        if (myFragment.isAdded()){
            return;
        }

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.myFragment,myFragment);
        fragmentTransaction.commit();

        myPrefs.name().put("John");

        myPrefs.edit()
                .name()
                .put("John")
                .age()
                .put(42)
                .apply();

        // Preference clearing:
        myPrefs.clear();

        // Check if a value exists:
        boolean nameExists = myPrefs.name().exists();

        // Reading a value
        long lastUpdated = myPrefs.lastUpdated().get();

       // Reading a value and providing a fallback default value
        long now = System.currentTimeMillis();
        long lastUpdat = myPrefs.lastUpdated().getOr(now);
        downloadImage();


    }

    //开启一个子线程
    @Background
    void getData(){
        update("更新内容");
    }

    /***
     *
     * If propagation = REUSE, the method will check first if it is inside the
     * UI thread already.
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void update(@NonNull String update){
        txt_configuration2.setText(update);
    }

    @UiThread
    void toast(@StringRes int StringId ){
        Toast.makeText(this, getString(StringId), Toast.LENGTH_SHORT).show();
    }

    /**
     * 使用Receiver注解，会在ConfigurationTestActivity_类中自动进行注册 及反注册
     * onAction方法将会在onReceive调用
     * actions 用来注册action行为
     * @param intent 同
     * @param context
     */
    @Receiver(actions = {"com.eric.windows.update"},dataSchemes = {"data"})
    protected void onAction(Intent intent,Context context) {
        Toast.makeText(context, intent.getStringExtra("intent_data"), Toast.LENGTH_SHORT).show();
        txt_configuration5.setText(intent.getStringExtra("intent_data"));

    }

    @Click({R.id.txt_configuration,R.id.btn_custom_c})
    void onClick(View view){
        switch (view.getId()){
            case R.id.txt_configuration:
                Intent intent = new Intent(this,CircleTestActivity_.class);
                intent.putExtra("myStringExtra","Extra测试");
                startActivityForResult(intent,0x11);
                break;
            case R.id.btn_custom_c:
                Toast.makeText(this, "哦，我被点击了", Toast.LENGTH_SHORT).show();
                break;
        }

    }


    @OnActivityResult(0x11)
    void onResult(int resultCode, Intent data) {
        txt_configuration4.setText(data.getStringExtra("intent_data"));
    }

    @Background
    void downloadImage(){
        HttpGet get =new HttpGet("http://img2.pconline.com.cn/pconline/0706/19/1038447_34.jpg");
        try {
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = httpClient .execute(get);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity httpEntity = response.getEntity();
                final Bitmap bitmap  = BitmapFactory.decodeStream(httpEntity.getContent());
                AATestActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
